package teach.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import teach.aistar.model.entity.Commit;
import teach.aistar.model.vo.Result;
import teach.aistar.service.ICommitService;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class CommitController {
    @GetMapping("/commit")
    public String commit(){
        return "/login/commit";
    }

    @Autowired
    private ICommitService commitService;

    @PostMapping("/com")
    @ResponseBody
    public Result Insert(@Validated Commit commit, BindingResult bindingResult, HttpServletRequest req){
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        Map<String,String> errorsMap = new HashMap<>();

        if(null!=fieldErrorList && fieldErrorList.size()>0){
            for (FieldError f : fieldErrorList) {
                System.out.print(f.getField()+"=>");
                System.out.println(f.getDefaultMessage());
                String x = f.getDefaultMessage();

                errorsMap.put(f.getField(),f.getDefaultMessage());
            }

            req.setAttribute("errors",errorsMap);






            return new Result("500","添加失败",errorsMap);
        }
        else
        {
            System.out.println(commit);

            int commits = commitService.insert(commit);

            if(commits >0) {
                commitService.insert(commit);
                return new Result("200", "添加成功", null);
            }
            else
            {
                return new Result("401", "用户名已经存在，请重新注册", null);
            }
        }
    }

}
